<?php

namespace App\Services;

use App\Caches\User as UserCache;
use App\Models\User as UserModel;
use App\Repos\User as UserRepo;
use App\Services\Auth as AuthService;
use App\Services\Logic\Notice\AccountLogin as AccountLoginNoticeService;
use Phalcon\Di as Di;

class User extends Service
{
    protected $useCache = true;

    public function useCache($useCache = true): User
    {
        $this->useCache = $useCache;
        return $this;
    }

    public function get($id): ?UserModel
    {
        if ($this->useCache) {
            $cache = new UserCache();
            return $cache->get($id);
        } else {
            $repo = new UserRepo();
            return $repo->findById($id);
        }
    }

    public function login(UserModel $user): string
    {
        $service = new AccountLoginNoticeService();

        $service->createTask($user);

        /**
         * @var AuthService $auth
         */
        $auth = Di::getDefault()->get('auth');

        $token = $auth->saveAuthInfo($user);

        return $token;
    }
}